# global_exception_handler_controller.py
from flask import jsonify

from commons.entity.enum.response_code_enum import ResponseCodeEnum
from commons.entity.vo.response_vo import ResponseVO
from commons.exception.business_exception import BusinessException


class GlobalExceptionHandlerController:

    @staticmethod
    def register_global_exception_handlers(app):
        @app.errorhandler(Exception)
        def handle_exception(e):
            """
            全局异常处理器，捕获所有异常
            :param e: 捕获到的异常
            :return: 错误的响应数据
            """
            response = ResponseVO()

            # 404 错误
            if isinstance(e, FileNotFoundError):
                response.code = ResponseCodeEnum.CODE_404.code
                response.info = ResponseCodeEnum.CODE_404.msg
                response.status = "error"

            # 业务异常 (BusinessException)
            elif isinstance(e, BusinessException):
                print("BusinessException")
                response.code = e.code if e.code else ResponseCodeEnum.CODE_600.code
                response.info = e.message
                response.status = "error"

            # 参数类型错误
            elif isinstance(e, ValueError):
                response.code = ResponseCodeEnum.CODE_600.code
                response.info = ResponseCodeEnum.CODE_600.msg
                response.status = "error"

            # 主键冲突
            elif isinstance(e, KeyError):
                response.code = ResponseCodeEnum.CODE_601.code
                response.info = ResponseCodeEnum.CODE_601.msg
                response.status = "error"

            # 其他未知错误
            else:
                response.code = ResponseCodeEnum.CODE_500.code
                response.info = ResponseCodeEnum.CODE_500.msg
                response.status = "error"

            return jsonify(response.to_dict())
